#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"
using namespace ThreadModel;
std::string ip;
uint16_t port;
int sockfd = -1;
pthread_t tid;
// 线程发消息
void Send()
{
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    while (true)
    {
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input);
        
        int n = sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));
        (void)n;
        if(input=="QUIT")
        {
            pthread_cancel(tid);
            break;
        }
    }
}

// 收信息
void Recv()
{
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "pelase ./server ip port" << std::endl;
        exit(2);
    }
    port = std::stoi(argv[2]);
    ip = argv[1];
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    Thread t1(Send);
    Thread t2(Recv);
    t1.start();
    t2.start();
    tid = t2.Gettid();
    t1.Join();
    t2.Join();
    close(sockfd);
    return 0;
}